import base64
import json
import random
import re
import time
from urllib.parse import quote

import requests
from PIL import Image
from django.shortcuts import render
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from tools.IdentityCard import idc
from tools.SFLogin import f, DingDing
from tools.SendMessage import send_message
from tools.myjwt import mjwt
from tools.myredis import r
from tools.recognition import face
from user import models
from tools.qiniu import upload_qiniu


# Create your views here.

class SendCode(APIView):
    """
    发送验证码
    """

    def get(self, request):
        phone = request.query_params.get("phone")
        code = random.randint(1000, 9999)
        # if re.match(r"^1[3-9]\d{9}$", phone):
        #     data = json.loads(send_message(phone, code, 3))
        #     if data["statusCode"] == '000000':
        #         r.setex_str(phone, 120, code)
        #         return Response({"code": 200, "msg": "发送成功"})
        #     else:
        #         return Response({"code": 400, "msg": "发送失败"})
        r.setex_str(phone, 120, code)
        return Response({"code": 200, "msg": "发送成功", "data": code})


class CodeLoginView(APIView):
    """
    验证码登录
    """

    def post(self, request):
        """
        用户登录
        :param request:
        :return:
        """
        phone = request.data.get("phone")
        code = request.data.get("code")
        if phone is None:
            return Response({"code": 400, "msg": "登录失败"})
        if code is None:
            return Response({"code": 400, "msg": "登录失败"})
        if r.get_str(phone) == code:
            user = models.User.objects.filter(phone=phone).first()
            if user is None:
                user = models.User.objects.create(username=phone, password=phone, phone=phone)
            payload = {"userid": user.id, "username": user.username, "exp": int(time.time()) + 60 * 60 * 2}
            token = mjwt.jwt_encode(payload)
            payload["exp"] = int(time.time() + 60 * 60 * 3)
            retoken = mjwt.jwt_encode(payload)
            query = {"userid": {payload['userid']}, "username": {payload['username']}, "token": {token},
                     "retoken": {retoken}}
            return Response({"code": 200, "msg": "登录成功", "data": query})
        return Response({"code": 400, "msg": "登录失败"})


class PasLogingView(APIView):
    """
    密码登录
    """

    def post(self, request):
        phone = request.data.get("phone")
        password = request.data.get("password")
        user = models.User.objects.filter(phone=phone, password=password).first()
        if user:
            payload = {"userid": user.id, "username": user.username, "exp": int(time.time()) + 60 * 60 * 2}
            token = mjwt.jwt_encode(payload)
            payload["exp"] = int(time.time() + 60 * 60 * 3)
            retoken = mjwt.jwt_encode(payload)
            query = {"userid": {payload['userid']}, "username": {payload['username']}, "token": {token},
                     "retoken": {retoken}}
            return Response({"code": 200, "msg": "登录成功", "data": query})
        elif models.User.objects.filter(phone=phone):
            return Response({"code": 400, "msg": "密码错误"})
        return Response({"code": 400, "msg": "用户不存在"})


class DingLoginView(APIView):
    """
    第三方登录
    """

    def post(self, request):
        """
        用户登录
        :param request:
        :return:
        """
        types = request.data.get("types")
        print(types)
        r.set_str("types", types)
        factory = f.create_login(types)
        url = factory.get_url()
        return Response({"code": 200, "msg": "登录成功", "url": url})


class LoginCallbackView(APIView):
    """
    用户登录回调
    """

    def get(self, request):
        """
        用户登录回调
        :param request:
        :return:
        """
        types = r.get_str("types")
        print(types)
        factory = f.create_login(types)
        query = factory.roll_bcak(request)
        return Response(
            {"code": 200, "data": "回调成功", "query": query})


class IdCardView(APIView):
    def get(self, request):
        urllist = request.query_params.get("urllist")
        if not urllist:
            return Response({"code": 400, "error": "URL parameter is required"}, status=400)

        res = idc.main(urllist)
        if "error" in res:
            return Response({"code": 500, "error": res["error"]}, status=500)

        return Response({"code": 200, "data": res}, status=200)


class FaceView(APIView):
    def post(self, request):
        # 从请求中获取上传的文件
        img1 = request.data.get("img1")
        img2 = request.data.get("img2")
        print(img1)
        print(img2)

        # 检查文件是否上传
        if not img1 or not img2:
            return Response({"code": 400, "error": "img1 and img2 are required"}, status=status.HTTP_400_BAD_REQUEST)

        # 将上传的文件转换为 Base64 编码
        # img1_base64 = base64.b64encode(img1.read()).decode('utf-8')
        # img2_base64 = base64.b64encode(img2.read()).decode('utf-8')

        # 创建 Face 实例并调用 main 方法
        # res = face.main(img1_base64, img2_base64)
        res = face.main(img1, img2)

        # 检查是否有错误发生
        if "error" in res:
            return Response({"code": 500, "error": res["error"]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 返回结果
        return Response({"code": 200, "data": res}, status=status.HTTP_200_OK)


class UploadView(APIView):
    def post(self, request):
        file = request.FILES.get("file")
        url = upload_qiniu(file, file.name)
        return Response({"code": 200, "data": "上传成功", "url": url})
